package insight.sm.db;

import insight.common.Encrypter;
import insight.common.logging.JLogger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class DBManager {

	private static Logger logger = JLogger.getLogger("StratupLog");

	private DriverManagerDataSource dataSource;
	private Connection connection;
	
	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	public DriverManagerDataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DriverManagerDataSource dataSource) {
		this.dataSource = dataSource;
	}

	private JdbcTemplate template;

	public DBManager(String driver, String url, String user, String password) throws SQLException {
		try {
			
			Class.forName(driver);

			dataSource = new DriverManagerDataSource();
			dataSource.setDriverClassName(driver);
			dataSource.setUrl(url);
			dataSource.setUsername(user);
			dataSource.setPassword(decrypt(password));
			template = new JdbcTemplate(dataSource);
			connection = DriverManager.getConnection(url, user, password);
			
			System.out.println("connect");
		} catch (ClassNotFoundException e) {
			logger.log(Level.SEVERE,
					"Application startup failed, driver class " + driver
							+ " could not be loaded.", e);
		}
	}

	private String decrypt(String inStr) {
		try {
			return Encrypter.decrypt(inStr);
		} catch (Exception ex) {

		}
		return inStr;
	}

	public String getStringInClause(String[] ary) {
		String clause = "(";
		for (String st : ary) {
			clause += "'" + st + "',";
		}
		if (clause.lastIndexOf(",") > 0)
			clause = clause.substring(0, clause.lastIndexOf(","));
		clause += ") ";
		return clause;
	}

	public JdbcTemplate getTemplate() {
		return template;
	}

	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}

	public Connection getConnection() throws SQLException {
		if(connection!=null)
			return connection;
		return null;
	}

}
